package com.application.chiettinhdienluc.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.VatTuInfoAdapter;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.db.VatTuChiTietDataSource;
import com.application.chiettinhdienluc.model.NhanCongChiTietModel;
import com.application.chiettinhdienluc.model.VatTuChiTietModel;
import com.application.chiettinhdienluc.utils.CalculationUtils;
import com.application.chiettinhdienluc.utils.Log;
import com.application.chiettinhdienluc.utils.Utils;

public class VattuInfoFragmentActivity extends FragmentActivity {

	public static class VattuInfoFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<VatTuChiTietModel>> {
		private final String TAG = VattuInfoFragment.class.getSimpleName();
		private Resources res;
		private ListView lvVattu;
		// private ListView lvVattuSelect;
		private TextView tv_cpvt_value;
		private final Cursor c = null;
		VatTuInfoAdapter dataAdapter = null;
		//VattuSelectedAdapter dataSelectedAdapter = null;
		ArrayList<VatTuChiTietModel> vatTuList = new ArrayList<VatTuChiTietModel>();
		ArrayList<String> maVatTuListInDB = new ArrayList<String>();

		private ProgressBar pro_loading_vattu;

		private boolean UpdateListenerIsRegistered = false;
		private UpdateListener listener = null;
		private LinearLayout layout_total_value;
		private EditText edt_filter_vattu_info_list;
		private TextView tvfilter_vattu_info_result_count;
		private TextWatcher textChangeListener = null;

		// private ScrollView scrollView;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			getActivity().getWindow().setBackgroundDrawable(null);

		}

		/**
		 * The Fragment's UI
		 */
		@SuppressLint("ResourceAsColor")
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View v = inflater.inflate(R.layout.vattu_info, container, false);
			res = getResources();
			lvVattu = (ListView) v.findViewById(R.id.lvVattu);
			// lvVattuSelect = (ListView) v.findViewById(R.id.lvVattuSelect);
			tv_cpvt_value = (TextView) v.findViewById(R.id.tv_cpvt_value);
			pro_loading_vattu = (ProgressBar) v.findViewById(R.id.pro_loading_vattu);
			layout_total_value = (LinearLayout) v.findViewById(R.id.layout_total_value);
			// scrollView = (ScrollView) v.findViewById(R.id.scrollView);

		
			dataAdapter = new VatTuInfoAdapter(getActivity(), vatTuList);
			lvVattu.setAdapter(dataAdapter);

			
			// scrollView.scrollTo(0, 0);

			double cpvt = CalculationUtils.calculateChiPhiVatTu(vatTuList);
			tv_cpvt_value.setText(Utils.formatDoubleNumber(cpvt));
			GlobalData.ChiPhiVatTu = cpvt;
			
			edt_filter_vattu_info_list = (EditText) v.findViewById(R.id.edt_filter_vattu_info_list);
			tvfilter_vattu_info_result_count = (TextView)v.findViewById(R.id.tvfilter_vattu_info_result_count);
			textChangeListener = new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					dataAdapter.getFilter().filter(s, new Filter.FilterListener() {
						@Override
						public void onFilterComplete(int count) {
							tvfilter_vattu_info_result_count.setText(String.format(
									res.getString(R.string.str_filter_result_count),
									count));
						}
					});
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub
				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
				}
			};
			
			edt_filter_vattu_info_list.addTextChangedListener(textChangeListener);

			// getListViewSize(lvVattu);

			// displayListView();
			// pro_loading_vattu.setVisibility(View.VISIBLE);
			// layout_total_value.setVisibility(View.GONE);
			// lvVattu.setVisibility(View.GONE);
			getLoaderManager().initLoader(0, null, this);
			return v;
		}

		// public static void getListViewSize(ListView myListView) {
		// ListAdapter myListAdapter = myListView.getAdapter();
		// if (myListAdapter == null) {
		// // do nothing return null
		// return;
		// }
		// // set listAdapter in loop for getting final size
		// int totalHeight = 0;
		// for (int size = 0; size < myListAdapter.getCount(); size++) {
		// View listItem = myListAdapter.getView(size, null, myListView);
		// listItem.setLayoutParams(new
		// ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
		// LayoutParams.WRAP_CONTENT));
		// listItem.measure(0, 0);
		// totalHeight += listItem.getMeasuredHeight();
		// }
		// // setting listview item in adapter
		// ViewGroup.LayoutParams params = myListView.getLayoutParams();
		// params.height = totalHeight + (myListView.getDividerHeight() *
		// (myListAdapter.getCount() - 1));
		// myListView.setLayoutParams(params);
		// // print height of adapter on log
		// }

		@Override
		public void onResume() {
			// TODO Auto-generated method stub
			super.onResume();

			if (!UpdateListenerIsRegistered && listener != null) {
				IntentFilter intentFilter = new IntentFilter();
				intentFilter.addAction("com.application.chiettinhdienluc.ui.RefreshVattuInfo");
				intentFilter.addAction("com.application.chiettinhdienluc.ui.SaveVattuInfo");
				intentFilter.addAction(VatTuInfoAdapter.Selected_VatTu_Change);
				getActivity().registerReceiver(listener, intentFilter);
				UpdateListenerIsRegistered = true;
			}

		}

		@Override
		public void onPause() {
			// TODO Auto-generated method stub
			try {
				if (UpdateListenerIsRegistered && listener != null) {
					getActivity().unregisterReceiver(listener);
					UpdateListenerIsRegistered = false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.onPause();
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			res = getResources();
			listener = new UpdateListener();
		}

		@Override
		public Loader<List<VatTuChiTietModel>> onCreateLoader(int arg0, Bundle arg1) {
			// TODO Auto-generated method stub
			return new AppListLoader(getActivity());
		}

		@Override
		public void onLoadFinished(Loader<List<VatTuChiTietModel>> arg0, List<VatTuChiTietModel> arg1) {
			// TODO Auto-generated method stub
			vatTuList = new ArrayList<VatTuChiTietModel>(arg1);
			
			Collections.sort(vatTuList, new Comparator<VatTuChiTietModel>() {
				public int compare(VatTuChiTietModel obj1, VatTuChiTietModel obj2) {
					// TODO Auto-generated method stub
					return (obj1.getOrder() < obj2.getOrder()) ? -1 : (obj1.getOrder() > obj2.getOrder()) ? 1 : (obj1.getTenVatTu().compareToIgnoreCase(obj2.getTenVatTu()));
				}
			});
			
			dataAdapter.setItemList(vatTuList);
			dataAdapter.notifyDataSetChanged();
			
			double cpvt = CalculationUtils.calculateChiPhiVatTu(vatTuList);
			tv_cpvt_value.setText(Utils.formatDoubleNumber(cpvt));
			GlobalData.ChiPhiVatTu = cpvt;
			
			tvfilter_vattu_info_result_count.setText(String.format(
					res.getString(R.string.str_filter_result_count),
					dataAdapter.getCount()));
			
			Intent i = new Intent();
//			i.setAction("com.application.chiettinhdienluc.ui.result_change");
			i.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelResultInfo");
			i.putExtra("UpdateDataForResultTab", true);
			MainApplication.getAppContext().sendBroadcast(i);
			// getListViewSize(lvVattu);
			// pro_loading_vattu.setVisibility(View.GONE);
			// lvVattu.setVisibility(View.VISIBLE);
			// layout_total_value.setVisibility(View.VISIBLE);
		}

		@Override
		public void onLoaderReset(Loader<List<VatTuChiTietModel>> arg0) {
			// TODO Auto-generated method stub

		}

		protected class UpdateListener extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				try {

					if (intent != null && !TextUtils.isEmpty(intent.getAction())) {
						String action = intent.getAction();

						if (!TextUtils.isEmpty(action)) {
							if (action.equals("com.application.chiettinhdienluc.ui.RefreshVattuInfo")) {
								// updateDisplayInfoGlobal();
								getLoaderManager().restartLoader(0, null, VattuInfoFragment.this);
								if(GlobalData.SelectedVatTuList != null)  
									GlobalData.SelectedVatTuList.clear();

							} else if (action.equals("com.application.chiettinhdienluc.ui.SaveVattuInfo")) {
								VatTuChiTietDataSource dbHelper = new VatTuChiTietDataSource();

								for (int i = 0, n = dataAdapter.getCount(); i < n; i++) {
									VatTuChiTietModel item = (VatTuChiTietModel) dataAdapter.getItem(i);
									item.setMaDonViQuanLy(MainApplication.getMaDonViQuanLy());

									if (item.getSoLuong() > 0) {
										dbHelper.updateValue(item);
									} else {
										dbHelper.deleteItemWithQuantityZero(item, true);
									}
								}

								Intent broadcastIntent1 = new Intent();
								broadcastIntent1.setAction("com.application.chiettinhdienluc.ui.SaveNhanCongInfo");
								MainApplication.getAppContext().sendBroadcast(broadcastIntent1);
								
							} else if (action.equalsIgnoreCase(VatTuInfoAdapter.Selected_VatTu_Change)) {
								if (intent.getExtras().getBoolean("Selected_VatTu_Change")) {

								
									double cpvt = CalculationUtils.calculateChiPhiVatTu(GlobalData.SelectedVatTuList);
									
									
									tv_cpvt_value.setText(Utils.formatDoubleNumber(cpvt));
									GlobalData.ChiPhiVatTu = cpvt;

//									CalculationUtils.calculate(GlobalData.globalChietTinh, (long) GlobalData.ChiPhiVatTu, (long) GlobalData.ChiPhiNhanCong);

									Intent i = new Intent();
//									i.setAction("com.application.chiettinhdienluc.ui.result_change");
									i.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelResultInfo");
									i.putExtra("UpdateDataForResultTab", true);
									MainApplication.getAppContext().sendBroadcast(i);

								} else {
									Log.v("HAI", "set adapter fail");
								}
							} else if (action.equals("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelVattuInfo")) {

							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static class AppListLoader extends AsyncTaskLoader<List<VatTuChiTietModel>> {

		List<VatTuChiTietModel> mVatTuChiTiets;

		public AppListLoader(Context context) {
			super(context);

			// Retrieve the package manager for later use; note we don't
			// use 'context' directly but instead the save global application
			// context returned by getContext().
		}

		@Override
		public List<VatTuChiTietModel> loadInBackground() {
			// Retrieve all known applications.
//			final Context context = getContext();

			// Create corresponding array of entries and load their labels.
			List<VatTuChiTietModel> entries = new ArrayList<VatTuChiTietModel>();

			VatTuChiTietDataSource dbHelper = new VatTuChiTietDataSource();

			entries = dbHelper.getVatTuChiTietByHoSoId(GlobalData.globalChietTinh.get_Id());
			GlobalData.vattuInfoListInDB.clear();
			for(int i = 0, n = entries.size(); i < n; i++)
			{
				GlobalData.vattuInfoListInDB.add(entries.get(i).getMaVatTu());
				
				if(GlobalData.SelectedVatTuList != null && GlobalData.SelectedVatTuList.contain(entries.get(i).getMaVatTu()))
				{
					VatTuChiTietModel item = GlobalData.SelectedVatTuList.get(entries.get(i).getMaVatTu());
					
					if(item != null)
					{
						entries.get(i).setSoLuong(item.getSoLuong());
						entries.get(i).setCheck(item.getSoLuong() > 0);
						
						if(entries.get(i).isCheck()) 
							entries.get(i).setOrder(0);
						else
							entries.get(i).setOrder(1);
					}
				}
			}
			
			Log.i("VatTuChiTietModel number", entries.size() + " ");
			// Done!
			return entries;
		}

		/**
		 * Called when there is new data to deliver to the client. The super
		 * class will take care of delivering it; the implementation here just
		 * adds a little more logic.
		 */
		@Override
		public void deliverResult(List<VatTuChiTietModel> datas) {
			if (isReset()) {
				// An async query came in while the loader is stopped. We
				// don't need the result.
				if (datas != null) {
					onReleaseResources(datas);
				}
			}
			List<VatTuChiTietModel> oldDatas = datas;
			mVatTuChiTiets = datas;

			if (isStarted()) {
				super.deliverResult(datas);
			}

			if (oldDatas != null) {
				onReleaseResources(oldDatas);
			}
		}

		/**
		 * Handles a request to start the Loader.
		 */
		@Override
		protected void onStartLoading() {
			// if (mVatTuChiTiets != null) {
			// // If we currently have a result available, deliver it
			// // immediately.
			// deliverResult(mVatTuChiTiets);
			// }

			// if (takeContentChanged() || mVatTuChiTiets == null) {
			// // If the data has changed since the last time it was loaded
			// // or is not currently available, start a load.
			// forceLoad();
			// }
			forceLoad();
		}

		/**
		 * Handles a request to stop the Loader.
		 */
		@Override
		protected void onStopLoading() {
			// Attempt to cancel the current load task if possible.
			cancelLoad();
		}

		/**
		 * Handles a request to cancel a load.
		 */
		@Override
		public void onCanceled(List<VatTuChiTietModel> datas) {
			super.onCanceled(datas);

			// At this point we can release the resources associated with 'apps'
			// if needed.
			onReleaseResources(datas);
		}

		/**
		 * Handles a request to completely reset the Loader.
		 */
		@Override
		protected void onReset() {
			super.onReset();

			// Ensure the loader is stopped
			onStopLoading();

			// At this point we can release the resources associated with 'apps'
			// if needed.
			if (mVatTuChiTiets != null) {
				onReleaseResources(mVatTuChiTiets);
				mVatTuChiTiets = null;
			}
		}

		/**
		 * Helper function to take care of releasing resources associated with
		 * an actively loaded data set.
		 */
		protected void onReleaseResources(List<VatTuChiTietModel> datas) {
			// For a simple List<> there is nothing to do. For something
			// like a Cursor, we would close it here.
		}
	}

}
